package com.adams.distributed.control;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class Sftp
{

	protected static final char pathSeparator_char = '/';
	protected static final String pathSeparator_str = "/";
	protected static final int defaultMaxMakeFolderTaskDealAmount = 100;
	protected static final int defaultMaxMakeFolderTaskAmount = 8;
	protected static final int defaultMinMakeFolderTaskAmount = 1;
	protected static final int defaultMaxMakeFileTaskDealAmount = 50;
	protected static final int defaultMaxMakeFileTaskAmount = 8;
	protected static final int defaultMinMakeFileTaskAmount = 1;

	protected static ExecutorService filecopyPool = new ThreadPoolExecutor(8,
			8, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
			new ThreadPoolExecutor.CallerRunsPolicy());

	protected String changePathSeparator(String path)
	{
		char[] chars = path.toCharArray();

		for (int i = 0; i < chars.length; i++)
		{
			if (chars[i] == '\\')
			{
				chars[i] = pathSeparator_char;
			}
		}

		String result = new String(chars);
		while (result.startsWith("/"))
		{
			result = result.substring(1);
		}
		while (result.endsWith("/"))
		{
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}

	protected int needMakeFolderTaskAmount(int folderAmount)
	{
		int folderTaskAmount = folderAmount
				/ defaultMaxMakeFolderTaskDealAmount;
		if (folderTaskAmount > defaultMaxMakeFolderTaskAmount)
		{
			return defaultMaxMakeFolderTaskAmount;
		}
		if (folderTaskAmount < defaultMinMakeFolderTaskAmount)
		{
			return defaultMinMakeFolderTaskAmount;
		}

		return folderTaskAmount;
	}

	protected int needMakeFileTaskAmount(int fileAmount)
	{
		int folderTaskAmount = fileAmount / defaultMaxMakeFileTaskDealAmount;
		if (folderTaskAmount > defaultMaxMakeFileTaskAmount)
		{
			return defaultMaxMakeFileTaskAmount;
		}
		if (folderTaskAmount < defaultMinMakeFileTaskAmount)
		{
			return defaultMinMakeFileTaskAmount;
		}

		return folderTaskAmount;
	}

	public abstract boolean put(String src, String dist, boolean cleanBeforeCopy);

	public abstract boolean get(String src, String dist, boolean cleanBeforeCopy);

	public abstract void disconnect();
}
